from django.contrib.auth.hashers import make_password
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from user.forms import RegisterVerifyForm, LoginVerifyForm
from user.models import User
from utils.function import login_check


def user_center_info(request):
    if request.method == 'GET':
        return render(request,'user_center_info.html')


def user_center_order(request):
    if request.method == 'GET':
        return render(request,'user_center_order.html')


def user_center_site(request):
    if request.method == 'GET':
        return render(request,'user_center_site.html')

def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    if request.method == "POST":

        # if request.POST.get('allow'):
        #     form = RegisterVerifyForm(request.POST)
        #     if form.is_valid():
        #         User.objects.create(username=form.cleaned_data.get('user_name'),
        #                             password=form.cleaned_data.get('pwd'),
        #                             email=form.cleaned_data.get('email'))
        #         return HttpResponseRedirect(reverse('user:login'))
        #     else:
        #         return render(request,'register.html',{'errors':form.errors})
        # else:
        #     data = request.POST
        #     return render(request, 'register.html', {'data': data})
        data = request.POST
        form = RegisterVerifyForm(data)
        if form.is_valid():
            # 给密码加密
            password = make_password(form.cleaned_data.get('pwd'))
            # 实现注册
            User.objects.create(username=form.cleaned_data.get('user_name'),
                                password=password,
                                email=form.cleaned_data.get('email'))
            return HttpResponseRedirect(reverse('user:login'))
        else:
            return render(request,'register.html',{'errors':form.errors})


def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    if request.method == 'POST':
        form = LoginVerifyForm(request.POST)
        if form.is_valid():
            user = User.objects.filter(username=form.cleaned_data.get('username')).first()
            request.session['user_id'] = user.id
            return HttpResponseRedirect(reverse('goods:index'))
        else:
            return render(request,'login.html', {'errors':form.errors})



def logout(request):
    if request.method == 'GET':
        del request.session['user_id']
        return HttpResponseRedirect(reverse('user:login'))



